package service

import (
	"context"
	"flare-admin/db/dao"
	"flare-admin/service/cluster"
	"flare-admin/service/security"
	"sync"
)

var (
	// Svc 是service层Service的单例，http层通过该单例访问service层方法
	Svc           *Service
	singletonOnce sync.Once
)

func InitService(connectSource string) error {
	var err error
	singletonOnce.Do(func() {
		Svc, err = New(connectSource)
		if err == nil {
			// 初始化DDoS流量同步服务
			InitDDoSFlowSyncService(Svc)
			
			// // 初始化DDoS流量数据到数据库
			// ctx := context.Background()
			// if initErr := Svc.InitializeDDoSFlowsData(ctx); initErr != nil {
			// 	logrus.Warnf("[InitService] - failed to initialize DDoS flows data: %v", initErr)
			// 	// 不将初始化失败作为致命错误，允许服务继续运行
			// } else {
			// 	logrus.Infof("[InitService] - successfully initialized DDoS flows data")
			// }
		}
	})
	return err
}

// Service 为service层核心对象，其中封装各个模块的Service函数供http层调用
type Service struct {
	dao      *dao.DBTXQuery
	Cluster  *cluster.Service
	Security *security.Service
}

func New(connectSource string) (*Service, error) {
	ctx := context.Background()
	// conn, err := dao.NewDBConn(context.Background(), connectSource)
	// if err != nil {
	// 	return nil, err
	// }
	// if err = conn.Ping(ctx); err != nil {
	// 	return nil, err
	// }

	// return &Service{
	// 	dao: dao.NewDBTXQuery(conn),
	// }, nil
	pool, err := dao.NewDBPool(ctx, connectSource)
	if err != nil {
		return nil, err
	}
	if err = pool.Ping(ctx); err != nil {
		return nil, err
	}

	connPool := dao.NewDBTXQueryWithConnPool(pool)
	return &Service{
		dao:      connPool,
		Cluster:  cluster.New(connPool),
		Security: security.New(connPool),
	}, nil
}
